<template>
  <el-card>
    <div slot="header">
      <h3>维护商品SKU信息(包装)</h3>
    </div>
    <div>
      <el-row type="flex" justify="end">
        <el-button
          size="large"
          type="text"
          @click="$router.push({ name: 'commodityNotPerfection' })"
          >返回</el-button
        >
        <el-button
          size="large"
          type="text"
          :loading="loading.submit"
          @click="handleSaveData"
          >保存</el-button
        >
        <el-button
          size="large"
          type="text"
          :loading="loading.submit"
          @click="handleSubmitData"
          >提交</el-button
        >
      </el-row>
      <el-row class="item_wrap">
        <general-table
          :loading="loading.table"
          :data-source="tableData"
          :columns="tableColumns"
          @handleChangeInputNumber="handleChangeInputNumber"
        />
      </el-row>
    </div>
    <SelectUnitDialog
      :visible.sync="mainUnitVisible"
      @getUnitName="handleGetMainUnitName"
    />
    <!-- 选择产地弹框 -->
    <original-place-dialog
      :visible.sync="originalPlaceVisible"
      @getOriginalPlace="getOriginalPlaceFn"
    />
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
/* components */
import GeneralTable from '@/pages/commodity/modules/components/generalTable';
import SelectUnitDialog from '@/pages/commodity/components/SelectUnitDialog';
import OriginalPlaceDialog from '@/components/common/dialog/originalPlaceDialog';
/* constants */
import { singleAddSkuInfoColumnsFn } from '@/pages/commodity/modules/constants/skuInfoModule';
/* utils */
import { getSkuVolumnByCalculate } from '@/utils/getUtils';
import { isResponseSuccess } from '@/utils/bizUtils';
export default {
  components: {
    GeneralTable,
    SelectUnitDialog,
    OriginalPlaceDialog
  },
  data () {
    return {
      originalPlaceVisible: false,
      productUuid: '',
      mainUnitVisible: false, // 选择主计量单位弹框开关状态
      tableData: [], // 表格数据
      tableColumns: [], // 表格columns
      storageCurrentRowData: {}, // 存储当前操作row，用于主计量单位的赋值
      loading: {
        table: false, // 表格加载loading
        submit: false, // 提交按钮loading
      },
    }
  },
  created () {
    this.productUuid = this.$route.query.productUuid;
    this.initTableDataAction();
  },
  mounted () {
    this.tableColumns = _.cloneDeep(
      singleAddSkuInfoColumnsFn({
        handleChooseMainUnit: this.handleChooseMainUnit,
        handleChooseOriginalPlace: this.handleChooseOriginalPlace
      })
    );
  },
  methods: {
    /* 获取产地信息方法 */
    getOriginalPlaceFn (data) {
      let { producingAreaName, producingAreaCode } = data;
      let { index } = this.storageCurrentRowData;
      this.tableData[index].producingAreaName = producingAreaName;
      this.tableData[index].producingAreaCode = producingAreaCode;
    },
    /* 选择产地事件 */
    handleChooseOriginalPlace ({ index }) {
      this.storageCurrentRowData.index = index;
      this.originalPlaceVisible = true;
    },
    initTableDataAction () {
      let data = {};
      this.loading.table = true;
      ApiRequest(
        `/sysback/prepare/commit/package/queryPackage?productUuid=${this.productUuid}`,
        'post',
        data,
        false
      ).then(res => {
        this.loading.table = false;
        if (res.retStatus !== '1') { return false }
        let { main, packageList } = res.retData;
        this.tableData = packageList.reduce((value, row) => {
          row.singleVolume = getSkuVolumnByCalculate({ type: { start: 'single' }, row });
          row.oneVolume = getSkuVolumnByCalculate({ type: { start: 'one' }, row });
          row.twoVolume = getSkuVolumnByCalculate({ type: { start: 'two' }, row });
          row.threeVolume = getSkuVolumnByCalculate({ type: { start: 'three' }, row });
          value.push({
            ...main,
            ...row
          });
          return value;
        }, []);
      }).catch(() => {
        this.loading.table = false;
      })
    },
    /* 选择主计量单位 */
    handleChooseMainUnit (data) {
      this.storageCurrentRowData = data;
      this.mainUnitVisible = true;
    },
    handleGetMainUnitName (unitName) {
      let { type, index } = this.storageCurrentRowData;
      this.tableData[index][type] = unitName;
    },
    /* 计算体积 */
    handleChangeInputNumber (data) {
      let { row, columnName } = data;
      let typeSplit = _.lowerCase(columnName).split(' '); // 转换字符串string以空格分开单词，并转换为小写,并通过split切割成对应的数组
      let type = typeSplit[0]; // 只取第一项，分别对应 single one two three四种情况
      row[`${type}Volume`] = getSkuVolumnByCalculate({ type: { start: type }, row });
    },
    // 保存
    handleSaveData () {
      let mySubmitList = {
        productUuid: this.productUuid,
        packageList: this.tableData
      }
      this.loading.submit = true;
      ApiRequest(
        '/sysback/prepare/commit/package/savePackage',
        'post',
        mySubmitList,
        false
      ).then(res => {
        this.loading.submit = false;
        if (res.retStatus !== '1') { return false }
        this.$message.success('保存成功');
        this.$router.push({ name: 'commodityNotPerfection' });
      }).catch(() => {
        this.loading.submit = false;
      })
    },
    // 提交
    handleSubmitData () {
      this.submitCheckData({
        url: '/sysback/prepare/commit/package/checkAndSavePackage',
        data: {
          productUuid: this.productUuid,
          packageList: this.tableData
        }
      });
    },
    // 提交校验数据
    async submitCheckData ({ url, type = 'post', data = {}, isFormData = false }) {
      try {
        this.loading.submit = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.loading.submit = false;
        if (isResponseSuccess(res)) {
          const { isSuccess } = res.retData;
          if (isSuccess) {
            this.$message.success('提交成功');
            this.$router.push({ name: 'commodityNotPerfection' });
            return false;
          }
          this.$message.warning('存在异常信息');
          this.tableColumns = [
            { title: '异常信息', key: 'errorMsg', errorTip: true, notShowTip: true },
            ..._.cloneDeep(
              singleAddSkuInfoColumnsFn({
                handleChooseMainUnit: this.handleChooseMainUnit,
                handleChooseOriginalPlace: this.handleChooseOriginalPlace
              })
            )
          ]
          this.tableData = res.retData?.packageList;
        }
      } catch (err) {
        this.loading.submit = false;
      }
    }
  }
}
</script>
<style lang="less" scoped>
.item_wrap {
  margin: 10px 0px;
}
/deep/ .el-card__header {
  padding: 10px 20px;
}
</style>
